<template>
  <div class="admin-promotions-container">
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">促销管理</h2>
        <el-tag v-if="hasChanges" type="warning" effect="dark">有未保存的更改</el-tag>
      </div>
      <div class="header-actions">
        <el-button :disabled="!hasChanges" @click="resetSettings" plain>重置更改</el-button>
        <el-button type="primary" :disabled="!hasChanges" @click="saveSettings" :loading="saving">
          <el-icon><Check /></el-icon> 保存设置
        </el-button>
      </div>
    </div>

    <el-card class="main-card" shadow="hover">
      <el-tabs v-model="activeTab" type="border-card" stretch>
        <!-- 折扣设置 -->
        <el-tab-pane label="折扣设置" name="discount">
          <div class="tab-header">
            <h3>折扣功能配置</h3>
            <div class="feature-switch">
              <span class="switch-label">{{ promotionSettings.discount.enabled ? '已启用' : '已禁用' }}</span>
              <el-switch 
                v-model="promotionSettings.discount.enabled" 
                @change="onChange"
                active-color="#13ce66"
                inline-prompt
                :active-text="'开'"
                :inactive-text="'关'"
              />
            </div>
          </div>

          <div :class="{'disabled-section': !promotionSettings.discount.enabled}">
            <el-form label-position="top" class="promotion-form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="默认折扣类型">
                    <el-radio-group v-model="promotionSettings.discount.defaultType" @change="onChange" size="large">
                      <el-radio-button label="none">无折扣</el-radio-button>
                      <el-radio-button label="item">单品折扣</el-radio-button>
                      <el-radio-button label="order">整单折扣</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                
                <el-col :span="12">
                  <el-form-item label="整单折扣起步金额">
                    <div class="input-with-addon">
                      <el-input-number
                        v-model="promotionSettings.discount.minAmount"
                        :min="0"
                        :step="10"
                        controls-position="right"
                        @change="onChange"
                      />
                      <span class="input-addon">元</span>
                    </div>
                    <div class="form-help">设置客户消费满多少金额才能使用整单折扣</div>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item label="默认折扣力度">
                <div class="discount-slider">
                  <span class="discount-value">{{ (promotionSettings.discount.defaultValue / 10).toFixed(1) }}折</span>
                  <el-slider
                    v-model="promotionSettings.discount.defaultValue"
                    :min="50"
                    :max="100"
                    :step="5"
                    :format-tooltip="value => `${(value / 10).toFixed(1)}折`"
                    show-stops
                    @change="onChange"
                    class="discount-slider-component"
                  />
                </div>
              </el-form-item>
              
              <el-divider content-position="left">
                <el-tag type="info" effect="plain" size="large">单品折扣设置</el-tag>
              </el-divider>
              
              <div class="table-actions">
                <el-input
                  v-model="productSearch"
                  placeholder="搜索商品名称"
                  prefix-icon="Search"
                  clearable
                  style="width: 250px"
                />
                <div>
                  <el-button type="success" plain size="small" @click="enableAllDiscounts">
                    <el-icon><Select /></el-icon> 全部启用
                  </el-button>
                  <el-button type="danger" plain size="small" @click="disableAllDiscounts">
                    <el-icon><Close /></el-icon> 全部禁用
                  </el-button>
                </div>
              </div>
              
              <el-table 
                :data="filteredDiscountProducts" 
                border 
                style="width: 100%"
                :header-cell-style="{background:'#f5f7fa', color: '#606266'}"
                highlight-current-row
                max-height="400px"
              >
                <el-table-column prop="name" label="商品名称" min-width="150" />
                <el-table-column prop="price" label="原价" width="100">
                  <template #default="scope">
                    ¥{{ scope.row.price.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column label="折后价" width="120">
                  <template #default="scope">
                    <span v-if="scope.row.discount.enabled">
                      ¥{{ ((scope.row.price * scope.row.discount.value) / 100).toFixed(2) }}
                    </span>
                    <span v-else class="text-muted">无折扣</span>
                  </template>
                </el-table-column>
                <el-table-column label="启用折扣" width="120" align="center">
                  <template #default="scope">
                    <el-switch
                      v-model="scope.row.discount.enabled"
                      @change="() => { updateDiscountProduct(scope.row); onChange(); }"
                      active-color="#13ce66"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="折扣力度" width="160" align="center">
                  <template #default="scope">
                    <el-select 
                      v-model="scope.row.discount.value" 
                      placeholder="选择折扣"
                      :disabled="!scope.row.discount.enabled"
                      @change="onChange"
                      style="width: 100px"
                    >
                      <el-option
                        v-for="n in 6"
                        :key="n"
                        :label="`${(5 + n / 2).toFixed(1)}折`"
                        :value="50 + n * 5"
                      />
                    </el-select>
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </el-tab-pane>
        
        <!-- 买一送一设置 -->
        <el-tab-pane label="买一送一" name="buyOneGetOne">
          <div class="tab-header">
            <h3>买一送一功能配置</h3>
            <div class="feature-switch">
              <span class="switch-label">{{ promotionSettings.buyOneGetOne.enabled ? '已启用' : '已禁用' }}</span>
              <el-switch 
                v-model="promotionSettings.buyOneGetOne.enabled" 
                @change="onChange"
                active-color="#13ce66"
                inline-prompt
                :active-text="'开'"
                :inactive-text="'关'"
              />
            </div>
          </div>

          <div :class="{'disabled-section': !promotionSettings.buyOneGetOne.enabled}">
            <div class="table-actions">
              <el-input
                v-model="productSearchB1G1"
                placeholder="搜索商品名称"
                prefix-icon="Search"
                clearable
                style="width: 250px"
              />
              <div>
                <el-button type="success" plain size="small" @click="enableAllB1G1">
                  <el-icon><Select /></el-icon> 全部参与
                </el-button>
                <el-button type="danger" plain size="small" @click="disableAllB1G1">
                  <el-icon><Close /></el-icon> 全部取消
                </el-button>
              </div>
            </div>
            
            <div class="activity-description">
              <el-alert
                title="买一送一活动说明"
                type="info"
                description="选择参与买一送一的商品后，顾客购买该商品时，第二件同样商品将免费赠送。"
                show-icon
                :closable="false"
              />
            </div>
            
            <el-table 
              :data="filteredB1G1Products" 
              border 
              style="width: 100%"
              :header-cell-style="{background:'#f5f7fa', color: '#606266'}"
              highlight-current-row
              max-height="400px"
            >
              <el-table-column prop="name" label="商品名称" min-width="150" />
              <el-table-column prop="price" label="价格" width="120">
                <template #default="scope">
                  ¥{{ scope.row.price.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column label="参与买一送一" width="120" align="center">
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.buyOneGetOne"
                    @change="() => { updateBuyOneGetOneProduct(scope.row); onChange(); }"
                    active-color="#13ce66"
                  />
                </template>
              </el-table-column>
              <el-table-column label="活动效果" width="200">
                <template #default="scope">
                  <el-tag v-if="scope.row.buyOneGetOne" type="success">
                    买1送1（实际单价 ¥{{ (scope.row.price / 2).toFixed(2) }}）
                  </el-tag>
                  <span v-else class="text-muted">不参与活动</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
        
        <!-- 抹零设置 -->
        <el-tab-pane label="抹零设置" name="roundDown">
          <div class="tab-header">
            <h3>抹零功能配置</h3>
            <div class="feature-switch">
              <span class="switch-label">{{ promotionSettings.roundDown.enabled ? '已启用' : '已禁用' }}</span>
              <el-switch 
                v-model="promotionSettings.roundDown.enabled" 
                @change="onChange"
                active-color="#13ce66"
                inline-prompt
                :active-text="'开'"
                :inactive-text="'关'"
              />
            </div>
          </div>

          <div :class="{'disabled-section': !promotionSettings.roundDown.enabled}">
            <el-form label-position="top" class="promotion-form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="默认抹零方式">
                    <el-radio-group v-model="promotionSettings.roundDown.defaultType" @change="onChange" size="large">
                      <el-radio-button label="none">不抹零</el-radio-button>
                      <el-radio-button label="yuan">抹去元</el-radio-button>
                      <el-radio-button label="jiao">抹去角</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <div class="round-down-examples">
                <h4>抹零效果示例：</h4>
                <div class="example-container">
                  <div class="example-item">
                    <div class="example-title">不抹零</div>
                    <div class="example-value">¥98.76 → ¥98.76</div>
                    <div class="example-desc">保持原价不变</div>
                  </div>
                  <div class="example-item">
                    <div class="example-title">抹去角</div>
                    <div class="example-value">¥98.76 → ¥98.00</div>
                    <div class="example-desc">小数点后一位清零</div>
                  </div>
                  <div class="example-item">
                    <div class="example-title">抹去元</div>
                    <div class="example-value">¥98.76 → ¥90.00</div>
                    <div class="example-desc">个位及小数点后清零</div>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Check, Close, Select, Search } from '@element-plus/icons-vue'
import api from '@/utils/api'

// 当前激活的标签页
const activeTab = ref('discount')
const productSearch = ref('')
const productSearchB1G1 = ref('')
const saving = ref(false)
const hasChanges = ref(false)
const originalSettings = ref(null)

// 所有商品
const allProducts = ref([])

// 促销配置
const promotionSettings = reactive({
  discount: {
    enabled: true,
    defaultType: 'none', // none, item, order
    defaultValue: 90,    // 默认9折
    minAmount: 100       // 满100元可用
  },
  buyOneGetOne: {
    enabled: false,
    items: []  // 参与买一送一的商品ID
  },
  roundDown: {
    enabled: false,
    defaultType: 'none'  // none, yuan, jiao
  }
})

// 带有折扣设置的商品列表
const discountProducts = ref([])

// 根据搜索过滤的折扣商品列表
const filteredDiscountProducts = computed(() => {
  if (!productSearch.value) return discountProducts.value
  
  const keyword = productSearch.value.toLowerCase()
  return discountProducts.value.filter(product => 
    product.name.toLowerCase().includes(keyword)
  )
})

// 根据搜索过滤的买一送一商品列表
const filteredB1G1Products = computed(() => {
  if (!productSearchB1G1.value) return allProducts.value
  
  const keyword = productSearchB1G1.value.toLowerCase()
  return allProducts.value.filter(product => 
    product.name.toLowerCase().includes(keyword)
  )
})

// 全部启用/禁用折扣
const enableAllDiscounts = () => {
  discountProducts.value.forEach(product => {
    product.discount.enabled = true
  })
  onChange()
}

const disableAllDiscounts = () => {
  discountProducts.value.forEach(product => {
    product.discount.enabled = false
  })
  onChange()
}

// 全部启用/禁用买一送一
const enableAllB1G1 = () => {
  allProducts.value.forEach(product => {
    product.buyOneGetOne = true
    updateBuyOneGetOneProduct(product)
  })
  onChange()
}

const disableAllB1G1 = () => {
  allProducts.value.forEach(product => {
    product.buyOneGetOne = false
    updateBuyOneGetOneProduct(product)
  })
  onChange()
}

// 检测配置变化
const onChange = () => {
  hasChanges.value = true
}

// 重置更改
const resetSettings = () => {
  ElMessageBox.confirm('确定要放弃当前的更改吗？', '重置提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    if (originalSettings.value) {
      // 恢复原始设置
      Object.assign(promotionSettings, JSON.parse(originalSettings.value))
      
      // 更新商品的买一送一状态
      allProducts.value.forEach(product => {
        product.buyOneGetOne = promotionSettings.buyOneGetOne.items.includes(product.id)
      })
      
      hasChanges.value = false
      ElMessage.success('已重置为上次保存的设置')
    }
  }).catch(() => {})
}

// 获取所有商品
const fetchProducts = async () => {
  try {
    // 尝试加载API数据
    try {
      const response = await api.get('/products')
      if (response.data && response.data.status === 'success') {
        allProducts.value = response.data.data.map(product => ({
          ...product,
          buyOneGetOne: promotionSettings.buyOneGetOne.items.includes(product.id),
          discount: {
            enabled: false,
            value: 90 // 默认9折
          }
        }))
        
        // 初始化折扣商品列表
        discountProducts.value = [...allProducts.value]
        return
      }
    } catch (apiError) {
      console.log('API请求失败，使用硬编码数据', apiError)
    }
    
    // API请求失败，加载硬编码数据
    loadHardcodedProducts()
  } catch (error) {
    console.error('获取商品列表失败:', error)
    // 确保加载硬编码数据
    loadHardcodedProducts()
  }
}

// 加载硬编码商品数据（备用）
const loadHardcodedProducts = () => {
  allProducts.value = [
    {
      id: 1,
      name: '青岛啤酒',
      price: 8.0,
      buyOneGetOne: false,
      discount: { enabled: false, value: 90 }
    },
    {
      id: 2,
      name: '哈啤',
      price: 7.5,
      buyOneGetOne: false,
      discount: { enabled: false, value: 90 }
    },
    {
      id: 3,
      name: '科罗娜',
      price: 15.0,
      buyOneGetOne: false,
      discount: { enabled: false, value: 90 }
    },
    {
      id: 4,
      name: '1664白啤',
      price: 18.0,
      buyOneGetOne: false,
      discount: { enabled: false, value: 90 }
    },
    {
      id: 5,
      name: '精酿IPA',
      price: 25.0,
      buyOneGetOne: false,
      discount: { enabled: false, value: 90 }
    },
    {
      id: 6,
      name: '水果啤酒',
      price: 16.0,
      buyOneGetOne: false,
      discount: { enabled: false, value: 90 }
    }
  ]
  
  // 初始化折扣商品列表
  discountProducts.value = [...allProducts.value]
}

// 获取促销配置
const fetchPromotionSettings = async () => {
  try {
    // 尝试从API加载
    try {
      const response = await api.get('/promotion-settings')
      if (response.data && response.data.status === 'success') {
        // 更新促销配置
        Object.assign(promotionSettings, response.data.data)
        
        // 更新商品的买一送一状态
        allProducts.value.forEach(product => {
          product.buyOneGetOne = promotionSettings.buyOneGetOne.items.includes(product.id)
        })
        
        // 保存原始设置用于重置
        originalSettings.value = JSON.stringify(promotionSettings)
        return
      }
    } catch (apiError) {
      console.log('API请求失败，尝试从本地存储加载', apiError)
    }
    
    // 如果API未实现，尝试从本地存储加载
    const savedSettings = localStorage.getItem('promotionSettings')
    if (savedSettings) {
      const parsedSettings = JSON.parse(savedSettings)
      
      // 更新促销配置
      Object.assign(promotionSettings, parsedSettings)
      
      // 更新商品的买一送一状态
      allProducts.value.forEach(product => {
        product.buyOneGetOne = promotionSettings.buyOneGetOne.items.includes(product.id)
      })
      
      // 保存原始设置用于重置
      originalSettings.value = savedSettings
      
      console.log('从本地存储加载配置成功')
    } else {
      // 保存原始设置用于重置
      originalSettings.value = JSON.stringify(promotionSettings)
      console.log('使用默认促销配置')
    }
  } catch (error) {
    console.error('获取促销配置失败:', error)
    console.log('使用默认促销配置')
    // 保存原始设置用于重置
    originalSettings.value = JSON.stringify(promotionSettings)
  }
}

// 更新买一送一商品
const updateBuyOneGetOneProduct = (product) => {
  if (product.buyOneGetOne) {
    // 添加到买一送一商品列表
    if (!promotionSettings.buyOneGetOne.items.includes(product.id)) {
      promotionSettings.buyOneGetOne.items.push(product.id)
    }
  } else {
    // 从买一送一商品列表移除
    const index = promotionSettings.buyOneGetOne.items.findIndex(id => id === product.id)
    if (index !== -1) {
      promotionSettings.buyOneGetOne.items.splice(index, 1)
    }
  }
}

// 更新折扣商品
const updateDiscountProduct = (product) => {
  // 无需特殊处理，reactive对象会自动更新
  console.log('更新折扣商品:', product)
}

// 保存设置
const saveSettings = async () => {
  saving.value = true
  
  try {
    // 收集单品折扣设置
    const itemDiscounts = discountProducts.value
      .filter(product => product.discount.enabled)
      .map(product => ({
        productId: product.id,
        value: product.discount.value
      }))
    
    // 构建要保存的数据
    const settingsData = {
      discount: {
        ...promotionSettings.discount,
        itemDiscounts
      },
      buyOneGetOne: promotionSettings.buyOneGetOne,
      roundDown: promotionSettings.roundDown
    }
    
    // 保存到后端（目前后端未实现，这里模拟）
    try {
      const response = await api.post('/promotion-settings', settingsData)
      if (response.data && response.data.status === 'success') {
        ElMessage.success('促销设置保存成功')
        // 更新原始设置
        originalSettings.value = JSON.stringify(settingsData)
        hasChanges.value = false
        return
      }
    } catch (apiError) {
      console.log('API未实现，使用本地存储', apiError)
    }
    
    // API未实现，使用本地存储
    localStorage.setItem('promotionSettings', JSON.stringify(settingsData))
    // 更新原始设置
    originalSettings.value = JSON.stringify(settingsData)
    hasChanges.value = false
    ElMessage.success('促销设置保存成功')
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存促销设置失败')
  } finally {
    saving.value = false
  }
}

// 加载数据
onMounted(async () => {
  try {
    // 获取商品列表
    await fetchProducts()
    
    // 获取促销配置
    await fetchPromotionSettings()
    
    // 初始化不显示未保存状态
    hasChanges.value = false
    
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.warning('部分数据加载失败，使用默认配置')
    
    // 确保加载硬编码数据
    loadHardcodedProducts()
    
    // 保存原始设置用于重置
    originalSettings.value = JSON.stringify(promotionSettings)
  }
})
</script>

<style scoped>
.admin-promotions-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  font-size: 24px;
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.main-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.tab-header h3 {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.feature-switch {
  display: flex;
  align-items: center;
  gap: 10px;
}

.switch-label {
  font-size: 14px;
  color: #606266;
}

.disabled-section {
  opacity: 0.6;
  pointer-events: none;
  filter: grayscale(30%);
}

.promotion-form {
  max-width: 100%;
  margin-top: 20px;
}

.discount-slider {
  display: flex;
  align-items: center;
  gap: 20px;
}

.discount-value {
  font-size: 20px;
  font-weight: bold;
  color: #409EFF;
  min-width: 60px;
}

.discount-slider-component {
  flex-grow: 1;
}

.input-with-addon {
  display: flex;
  align-items: center;
}

.input-addon {
  margin-left: 10px;
  color: #606266;
}

.form-help {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.table-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.activity-description {
  margin-bottom: 20px;
}

.text-muted {
  color: #909399;
}

.round-down-examples {
  margin-top: 30px;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 4px;
}

.example-container {
  display: flex;
  justify-content: space-around;
  margin-top: 15px;
  flex-wrap: wrap;
  gap: 20px;
}

.example-item {
  text-align: center;
  padding: 15px;
  border-radius: 4px;
  background-color: white;
  min-width: 180px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.example-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #303133;
}

.example-value {
  font-size: 18px;
  color: #409EFF;
  margin-bottom: 10px;
}

.example-desc {
  font-size: 12px;
  color: #909399;
}
</style> 